package com.horoscope.astrology.zodiac.signs.free.activity

import android.app.Activity
import android.app.ActivityManager
import android.content.Context
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.view.*
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.ImageView
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.horoscope.astrology.zodiac.signs.free.AppSettingManager
import com.horoscope.astrology.zodiac.signs.free.R
import com.horoscope.astrology.zodiac.signs.free.utils.MyAnimationUtils
import com.horoscope.astrology.zodiac.signs.free.utils.ToastUtil
import com.horoscope.astrology.zodiac.signs.free.utils.ad.ad_business.ADInterstitialManager
import com.ironsource.mediationsdk.IronSource
import kotlinx.android.synthetic.main.item_loading.*

open class Base2Activity : AppCompatActivity() {

    private lateinit var rootView: RelativeLayout
    var isCurrentRunningForeground = true
    private var pendingCollapseKeyword = false
    private var focusedView: View? = null
    protected lateinit var mRecyclerView: androidx.recyclerview.widget.RecyclerView

    override fun onCreate(savedInstanceState: Bundle?) {
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE)
        super.onCreate(savedInstanceState)
        super.setContentView(R.layout.activity_base)

        rootView = findViewById(R.id.base_root)
    }

    override fun setContentView(layoutResID: Int) {
        val view = View.inflate(this, layoutResID, null)
        setContentView(view)
    }

    override fun setContentView(view: View?) {
        val params = RelativeLayout.LayoutParams(-1, -1)
        if (view != null) {
            rootView.addView(view, params)
        }
    }

    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        if (item?.itemId == android.R.id.home) {
            finish()
            return true
        }
        return super.onOptionsItemSelected(item)
    }


    override fun onStart() {
        super.onStart()
        if (!isCurrentRunningForeground) {
            isCurrentRunningForeground = true
            if (System.currentTimeMillis() - AppSettingManager.readLong(
                    "goto_back",
                    System.currentTimeMillis()
                ) > fiveMinute
            ) {
                startActivity(
                    SplashActivity
                        .generateIntent(this)
                )
            }
        }
    }

    override fun onResume() {
        super.onResume()
        IronSource.onResume(this)
    }

    override fun onPause() {
        super.onPause()
        ToastUtil.cancel()
        IronSource.onPause(this)
    }

    override fun onStop() {
        super.onStop()
        ToastUtil.cancel()
        isCurrentRunningForeground = isRunningForeground()
        if (!isCurrentRunningForeground) {
            AppSettingManager.saveLong(System.currentTimeMillis(), "goto_back")

        }
    }

    override fun onDestroy() {
        super.onDestroy()
        ToastUtil.cancel()
    }


    /**
     * Activity 全屏显示，不隐藏状态栏,覆盖于Activity之上   SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
     * Activity 不全屏显示 不隐藏状态栏，在Activity之上     SYSTEM_UI_FLAG_VISIBLE
     * Activity 全屏显示，隐藏状态栏                       INVISIBLE
     * Activity 全屏显示，状态栏被覆盖                     SYSTEM_UI_FLAG_FULLSCREEN
     * 窗台兰 背景设置
     * 虚拟按键 背景设置
     * systemUiVisibility : 状态栏和Activity间的位置关系
     */
    // 沉浸式状态栏，修改状态栏背景、内容颜色
    fun immersionWhite() {
        val window = window
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            //设置背景为白色时，status图标和navigation按键颜色
            window.decorView.systemUiVisibility =
                View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR or View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR
        }
//        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
//        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
        window.statusBarColor = Color.WHITE
        window.navigationBarColor = Color.WHITE
    }


    protected open fun dismissStatusBar(): Boolean {
        return false
    }

    open fun initTitleBar(context: Activity, backId: Int, titleId: Int, titleStr: String) {
        val back = findViewById<ImageView>(backId)
        back.setOnClickListener {
            context.finish()
        }
        val title = findViewById<TextView>(titleId)
        title.text = titleStr
    }


    open fun requestData() {

    }

    companion object {
        private const val fiveMinute = 5 * 60 * 1000
        fun getActivity(): Companion {
            return this
        }
    }

    // 检查app是否运行
    private fun isRunningForeground(): Boolean {
        val activityManager = this.getSystemService(Context.ACTIVITY_SERVICE) as (ActivityManager)
        val appProcessInfos = activityManager.runningAppProcesses ?: return false
        // 枚举进程,查看该应用是否在运行
        appProcessInfos.filter {
            it.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND
                    &&
                    it.processName == this.applicationInfo.processName
        }.forEach { _ ->
            return true
        }
        return false
    }

    // 显示Loading动画
    open fun showLoading() {
        frame_layout_loading_bg?.visibility = View.VISIBLE
        loading_out.visibility = View.VISIBLE
        loading?.visibility = View.VISIBLE
        loading?.startAnimation(MyAnimationUtils.loadingAnimation())
    }

    // 关闭Loading动画
    open fun showLoaded() {
        loading?.clearAnimation()
        frame_layout_loading_bg?.visibility = View.INVISIBLE
        loading_out?.visibility = View.INVISIBLE
        loading?.visibility = View.INVISIBLE
    }

    /**
     * EditText获取焦点并显示软键盘
     */
    open fun showSoftInputFromWindow(activity: Activity, editText: EditText) {
        editText.isFocusable = true
        editText.isFocusableInTouchMode = true
        editText.requestFocus()
        activity.window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE)
    }

    // 点击非输入框位置优先隐藏软键盘
    override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
        if (ev.action == MotionEvent.ACTION_DOWN) {
            pendingCollapseKeyword = isShouldHideInput(ev)
            if (pendingCollapseKeyword) focusedView = currentFocus
        } else if (ev.action == MotionEvent.ACTION_UP) {
            if (pendingCollapseKeyword) {
                val v = currentFocus
                if (v === focusedView) {
                    focusedView!!.clearFocus()
                    hideInput(this)
                }
            }
        }
        return super.dispatchTouchEvent(ev)
    }

    // 是否隐藏软键盘
    open fun isShouldHideInput(event: MotionEvent): Boolean {
        val v = currentFocus
        if (v is EditText) {
            val location = intArrayOf(0, 0)
            v.getLocationInWindow(location)
            return event.x < location[0] || event.x > location[0] + v.getWidth() || event.y < location[1] || event.y > location[1] + v.getHeight()
        }
        return false
    }

    // 收起键盘
    open fun hideInput(context: Context) {
        val imm = context
            .getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(focusedView!!.windowToken, 0)
    }

    // 展示键盘
    open fun showInput(et: EditText) {
        et.requestFocus()
        val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.showSoftInput(et, InputMethodManager.SHOW_IMPLICIT);
    }

    // 展示全屏广告
    open fun activityShowAd(text: String) {
        ADInterstitialManager.mInstance.showInterstitialAD(this, text)
    }

}